package com.kaidongyuan.app.kdydriverr.serviceAndReceiver;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.WindowManager;

import com.android.volley.RequestQueue;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;

import com.kaidongyuan.app.basemodule.utils.nomalutils.StringUtils;
import com.kaidongyuan.app.basemodule.widget.MLog;
import com.kaidongyuan.app.kdydriverr.R;
import com.kaidongyuan.app.kdydriverr.app.AppContext;
import com.kaidongyuan.app.kdydriverr.bean.Tools;
import com.kaidongyuan.app.kdydriverr.bean.order.LocationContineTime;
import com.kaidongyuan.app.kdydriverr.constants.Constants;
import com.kaidongyuan.app.kdydriverr.utils.LocationFileHelper;
import com.kaidongyuan.app.kdydriverr.utils.SharedPreferencesUtils;
import com.kaidongyuan.app.kdydriverr.utils.baidumapUtils.DataUtil;

import java.io.File;
import java.io.IOException;

/**
 * 后台定位服务
 *
 * @author ke
 */
public class VueTrackingScanService extends Service {

    private static final String TAG = "upLoad position ------ ";
    private final static String prefName = "configs";// shareprence中的配置名
    private Context mContext = this;
    //  public static final String Action_Tracking_Service = "com.kaidongyuan.app.kdydriver.service.TrackingService";
    public LocationClient mVueLocationClient;// 百度定位客户端
    public MyLocationListener myListener;// 百度定位监听
    private String tempcoor = "bd09ll";// 百度地图的编码模式
    private double mLat = 0, mLng = 0;
    //高精度模式
    private LocationMode tempMode = LocationMode.Hight_Accuracy;
    //仅GPS定位模式
//    private LocationMode tempMode = LocationMode.Device_Sensors;
    boolean isLoop = true;
    private static final double Min_Distance = 0;  // 上传时判断的最小距离
    //    private  static final double Min_Distance=-1;
    private RequestQueue mRequestQueue;
    private final static String Tag_Upload_Position = "Tag_Upload_Position";
    private boolean needClose =false;
    private String mUserId;
    private StopReceiver mReceiver;
    private String mFileName;
    //上传数据线程用到
    private long mNetNotConnetTime = 0;
    private android.os.Handler mHandler;
    private int mScanSpanTime = Constants.scanSpan;
    private Thread mThread;
    private boolean mLocationThreadRunning;
    private String locationaddress;//被定义为百度定位返回code码字段
    private boolean againBoolean=true;
    // private PowerManager.WakeLock wakeLock = null;

    private boolean isUpload = true; // 是否上传，防止20秒内上传多个点

    @Override
    public IBinder onBind(Intent intent) {
        MLog.i("\tTrackinSerice.onstart");
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        MLog.i("\tTrackinSerice.onstart");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("LM", "vue定位");
        Log.w("time", "TrackingService.onCreate");
        locationaddress="BDCode";
        mContext = this;
//        mVueLocationClient = new LocationClient(this);
//        myListener = new MyLocationListener();
//        mVueLocationClient.registerLocationListener(myListener);
//        initLocationClient();
        showNotification();
        try {
            mUserId=AppContext.getInstance().getUser().getIDX();
            if (mUserId==null||mUserId.isEmpty()){
                mUserId = SharedPreferencesUtils.getUserId();
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }

        mFileName = getApplicationContext().getFilesDir().getAbsolutePath()
                + File.separator + "Location" + File.separator + mUserId + ".log";
    }
    /*
     * 服务开始启动
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("LM", "vue定位onStartCommand");
        // acquireWakeLock();
        try {

            MLog.e("TrackingService.onStartCommand()");
            mUserId = SharedPreferencesUtils.getUserId();
            mFileName = getApplicationContext().getFilesDir().getAbsolutePath()
                    + File.separator + "Location" + File.separator + mUserId + ".log";
            mVueLocationClient = new LocationClient(this);
            myListener = new MyLocationListener();
            mVueLocationClient.registerLocationListener(myListener);
            initLocationClient();
                startLocate();


        }catch (Exception e){
            e.printStackTrace();
        }

        return START_STICKY;
    }


    /**
     * 定位SDK监听函数
     */
    private class MyLocationListener implements BDLocationListener {

        @RequiresApi(api = Build.VERSION_CODES.KITKAT_WATCH)
        @Override
        public void onReceiveLocation(BDLocation location) {
            Log.d("LM", "vue定位进入定位函数");
            SharedPreferences readLatLng = getSharedPreferences("w_UserInfo", MODE_MULTI_PROCESS);
            final String u = readLatLng.getString("UserName", "");
            final String a = location.getAddrStr();
            final String display = Tools.GetDisplayStatus(mContext);
            final String charging = Tools.GetChargingStatus(mContext);
            final String os = Build.VERSION.RELEASE + "|" + android.os.Build.MODEL + "|" + StringUtils.getVersionName(mContext);
            // 地址为null时不上传
            if(a == null) {
                return;
            }
            Log.d("LM", "vue定位准备上传: " );
            mLat = location.getLatitude();
            mLng = location.getLongitude();
            MLog.w( "首次定位"+"mLat:"+mLat+"\tmLng:"+mLng);
            getlocationReturnCode(location.getLocType(),location.getAddrStr());
            Log.d("LM", "vue首次定位: ");
            Log.d("LM", "vue定位地址: " + location.getAddrStr());
            Log.d("LM", "cellphone: " + u);
            Log.d("LM", "userName: " + "");
            Log.d("LM", "vehicleLocation: " + location.getAddrStr());
            Log.d("LM", "lon: " + location.getLongitude() + "");
            Log.d("LM", "lat: " + location.getLatitude() + "");
            Log.d("LM", "uuid: " + "android");
            Log.d("LM", "code: " + location.getLocType() + "");
            Log.d("LM", "brightscreen: " + display);
            Log.d("LM", "charging: " + charging);
            Log.d("LM", "os: " + os);
            Log.d("LM", "province: " + location.getProvince() + "");
            Log.d("LM", "city: " + location.getCity() + "");
            Log.d("LM", "district: " + location.getDistrict() + "");
            SharedPreferences p = mContext.getSharedPreferences("vueCurrLatLng", Context.MODE_PRIVATE);
            p.edit().putString("vue_w_lng",String.valueOf(location.getLongitude())).commit();
            p.edit().putString("vue_w_lat",String.valueOf(location.getLatitude())).commit();
            p.edit().putString("vue_w_address", location.getAddrStr()).commit();
            stopLocate();
        }
    }
    /**
     *调试是否成功定位的方法
     */
    private String getlocationReturnCode(int i,String address){
        Log.d("LM", "vue定位getlocationReturnCode");
        switch (i){
            case  -1:locationaddress="定位返回值为空|BD0";
                break;
            case  1: locationaddress="重定失败service没有启动|BD1";
                break;
            case   2:locationaddress="重定失败无监听函数|BD2";
                break;
            case   6:locationaddress="重定失败请求太频繁|BD6";
                break;
            case   7:locationaddress="请求百度定位连接失败|BD9";
                break;
            default:locationaddress=address+"|BD"+i;
                break;
        }
        return locationaddress;
    }
    private void closeService() {
        stopLocate();
        stopSelf();
        stopForeground(true);
        if (mReceiver != null) {
            try {
                unregisterReceiver(mReceiver);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    /**
     * 用于传递给服务端是排序用的id
     */
    private int saveCacheLocationId = 0;
    private void saveCacheLocation(double lat, double lng,String locationtime) {
        LocationContineTime location = new LocationContineTime();
        location.id = saveCacheLocationId+"";
        saveCacheLocationId++;
        if (mUserId == null) {
            mUserId = SharedPreferencesUtils.getUserId();
        }
        location.userIdx = (mUserId);
        location.ADDRESS = locationaddress;
        location.CORDINATEX = lat;
        location.CORDINATEY = lng;
        if (locationtime!=null){
            location.TIME=locationtime;
        }else {
            location.TIME = DataUtil.getStringTime(System.currentTimeMillis());
        }
        MLog.w("locationaddress"+locationaddress);
        locationaddress="BDCode";
        if (mFileName == null){
            mFileName = getApplicationContext().getFilesDir().getAbsolutePath()
                    + File.separator + "Location" + File.separator + mUserId + ".log";
        }
        File file = new File(mFileName);
        MLog.w("缓存文件位置.filePath:" + file.getAbsolutePath());
        if(!file.exists()){
            try {
                boolean makeFile = file.createNewFile();
                MLog.w( "TrackingService.saceCacheLocation.本地无缓存文件，创建缓存文件："+makeFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (!LocationFileHelper.saveInFile(location, mFileName)){
            // 离线存储点返回失败则排序id回退回去
            saveCacheLocationId--;
        }
    }
    public void showNotification(){
        //   NotificationManager manager= (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification.Builder builder=new Notification.Builder(mContext);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentTitle(getText(R.string.app_name));
//        builder.setContentText("正运输物流订单中，请保持App定位服务开启");
        Notification notification=builder.build();
        notification.flags=Notification.FLAG_ONGOING_EVENT;//标识正在运行的事件
        notification.flags|=Notification.FLAG_NO_CLEAR;//防止通知被点击清除
        notification.flags|=Notification.FLAG_HIGH_PRIORITY;//设置为高优先级的通知
        notification.flags|=Notification.FLAG_FOREGROUND_SERVICE;//表示正在运行的服务
        //   notification.defaults=Notification.DEFAULT_SOUND;//设置通知响铃
        //  notification.defaults|=Notification.DEFAULT_VIBRATE;//设置通知震动（配合相关授权）
        startForeground(R.string.app_name,notification);//以app_name的id为标识来启动和管理通知
        //  manager.notify(R.string.app_name,notification);//以app_name的id为标识来启动和管理通知
        MLog.i("*****showNotification**********");
    }
    /**
     * 初始化定位客户端
     */
    public void initLocationClient() {
        Log.d("LM", "vue定位initLocationClient");
        LocationClientOption option = new LocationClientOption();
        option.setProdName(mContext.getPackageName());
        MLog.w("ProdName:" + mContext.getPackageName());
        option.setCoorType(tempcoor);// 返回的定位结果是百度经纬度，默认值gcj02
        option.setLocationMode(tempMode);// 设置定位模式
        option.setScanSpan(mScanSpanTime);//设置上传位置时间间隔
        //  option.setScanSpan(1*60*1000);
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        option.setTimeOut(10 * 1000); // 网络定位的超时时间
        mVueLocationClient.setLocOption(option);
    }
    /**
     * 开始定位
     */
    public void startLocate() {
        Log.d("LM", "vue定位startLocate ");
        //  注释掉导致一次定位请求三次的现象
        if (mVueLocationClient != null && !mVueLocationClient.isStarted()) {
            mVueLocationClient.start();
            MLog.i("mLocationThread.sleep:"+mScanSpanTime);
        }else if (mVueLocationClient!=null){
            mVueLocationClient.requestLocation();
        }else {
            mVueLocationClient=new LocationClient(this);
            myListener=new MyLocationListener();
            mVueLocationClient.registerLocationListener(myListener);
            initLocationClient();
            mVueLocationClient.start();
        }
    }

    /**
     * 停止定位
     */
    public void stopLocate() {
        if (mVueLocationClient != null && mVueLocationClient.isStarted()) {
            mVueLocationClient.stop();
        }
    }

    @Override
    public void onDestroy() {
        isLoop = false;
        super.onDestroy();
        stopSelf();
        stopForeground(true);
        stopLocate();
        unregisterReceiver(mReceiver);
        // releaseWakeLock();
    }


    private class StopReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            needClose = true;
            mVueLocationClient.start();
        }
    }

    /**
     * 检测当前手机是否联网
     */
    public boolean isNetworkAvailable() {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo != null) {
            return mNetworkInfo.isAvailable();
        }
        return false;
    }

    private Dialog mNetDialog;
    /**
     * 显示 Dialog 提示用户连接网络
     */
    private void setContactNetDialog(){
        MLog.w("TrackingService.setContactNetDialog");
        if(mNetDialog==null){
            AlertDialog.Builder builder = new AlertDialog.Builder(getApplication());
            builder.setTitle(getText(R.string.app_name)+"提示：\n点击确定开启网络服务");
            builder.setCancelable(false);
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    mNetDialog.cancel();
                }
            });
            builder.setNegativeButton("取消",  new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mNetDialog.cancel();
                }
            });
            mNetDialog = builder.create();
            mNetDialog.getWindow().setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
        }
        mNetDialog.show();
    }
}